use serde::Deserialize;

use parrot_core::core::util::Util;

use crate::{ARGUMENT, CONFIG_FILE_NAME};

#[derive(Deserialize, Debug)]
pub struct Config {
    port: u16,
    unity_path: String,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            port: 5000,
            unity_path: "unity".to_string(),
        }
    }
}

impl Config {
    pub fn parse() -> Self {
        let p = &ARGUMENT
            .config_path
            .clone()
            .unwrap_or_else(|| Util::app_dirs().config_dir().join(CONFIG_FILE_NAME));

        let mut c: Config = std::fs::read_to_string(p)
            .ok()
            .and_then(|s| toml::from_str(&s).ok())
            .unwrap_or_default();

        if let Some(port) = &ARGUMENT.port {
            c.port = *port;
        }

        c
    }

    pub fn get_port(&self) -> u16 {
        self.port
    }

    pub fn get_unity_path(&self) -> &str {
        &self.unity_path
    }
}
